package com.turbo.cloud.ums.web.logic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.turbo.cloud.ums.web.entity.UmsApi;
import com.turbo.cloud.ums.web.service.IUmsApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import java.util.*;

/**
 * <p>
 * 初始化数据 逻辑处理类
 * </p>
 *
 * @author zhangluning
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class InitLogic {

    final IUmsApiService umsApiService;
    /**
     * Web上下文
     */
    final WebApplicationContext applicationContext;

    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 初始化接口配置
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean initApis() {
        //获取controller相关bean
        Map<String, RequestMappingHandlerMapping> map = applicationContext.getBeansOfType(RequestMappingHandlerMapping.class);
        map.forEach((key, value) -> {
            //获取method
            Map<RequestMappingInfo, HandlerMethod> methodMap = value.getHandlerMethods();
            //获取methodMap的key集合
            for (RequestMappingInfo info : methodMap.keySet()) {
                //controller url集合
                try {
                    String name = info.getName();
                    assert info.getPathPatternsCondition() != null;
                    Set<PathPattern> urlSet = info.getPathPatternsCondition().getPatterns();
                    Set<RequestMethod> methodSet = info.getMethodsCondition().getMethods();
                    //controller url拼接路由前缀
                    List<String> urlList = new ArrayList<>(urlSet.stream().map(path -> "/" + applicationName + path).toList());
                    List<String> methodList = new ArrayList<>(methodSet.stream().map(RequestMethod::name).toList());
                    if (!CollectionUtils.isEmpty(urlList) && !CollectionUtils.isEmpty(methodList)) {
                        String path = urlList.get(0);
                        String funName = path.substring(path.lastIndexOf("/") + 1);
                        String method = methodList.get(0);

                        LambdaQueryWrapper<UmsApi> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(UmsApi::getApiUrl, path);
                        List<UmsApi> apiList = umsApiService.list(queryWrapper);

                        if(!CollectionUtils.isEmpty(apiList)) {
                            for (UmsApi umsApi : apiList) {
                                umsApi.setApiTitle(name);
                                umsApi.setApiUrl(path);
                                umsApi.setApiCode(funName);
                                umsApi.setApiHttpMethod(method);
                                umsApi.setNote(name);
                                umsApiService.updateById(umsApi);
                            }
                        } else {
                            UmsApi umsApi = new UmsApi();
                            umsApi.setApiTitle(name);
                            umsApi.setApiUrl(path);
                            umsApi.setApiCode(funName);
                            umsApi.setApiHttpMethod(method);
                            umsApi.setNote(name);
                            umsApiService.save(umsApi);
                        }
                    } else {
                        if (!CollectionUtils.isEmpty(urlList)) {
                            log.info("URL链接::{}", urlList.get(0));
                        }
                        if (!CollectionUtils.isEmpty(methodList)) {
                            log.info("请求方式::{}", methodList.get(0));
                        }
                    }
                } catch (Exception e) {
                    log.error("初始化接口配置异常", e);
                }
            }
        });
        return true;
    }
}
